<template>
  <div class="page-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑运动记录' : '添加运动记录' }}</h2>
      <p>{{ isEdit ? '修改您的运动记录信息' : '记录您的运动活动' }}</p>
    </div>
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="exerciseForm" 
        :rules="rules" 
        label-width="100px"
        class="exercise-form"
      >
        <!-- 运动类型 -->
        <el-form-item label="运动类型" prop="exerciseTypeId">
          <el-select
            v-model="exerciseForm.exerciseTypeId"
            placeholder="选择运动类型"
            style="width: 100%"
            @change="handleTypeChange"
          >
            <el-option-group
              v-for="group in exerciseTypeGroups"
              :key="group.category"
              :label="getCategoryDisplayName(group.category)"
            >
              <el-option
                v-for="type in group.types"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        
        <!-- 开始时间 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="exerciseForm.startTime"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 8, 0, 0)"
            style="width: 100%"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <!-- 结束时间 -->
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="exerciseForm.endTime"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 9, 0, 0)"
            style="width: 100%"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <!-- 持续时间 -->
        <el-form-item label="持续时间" prop="durationMinutes">
          <el-input-number
            v-model="exerciseForm.durationMinutes"
            :min="1"
            :max="1440"
            :step="5"
            style="width: 100%"
            @change="handleDurationChange"
          >
            <template #suffix>分钟</template>
          </el-input-number>
        </el-form-item>
        
        <!-- 运动强度 -->
        <el-form-item label="运动强度" prop="intensity">
          <el-radio-group v-model="exerciseForm.intensity" @change="calculateCalories">
            <el-radio value="LOW">低强度</el-radio>
            <el-radio value="MEDIUM">中等强度</el-radio>
            <el-radio value="HIGH">高强度</el-radio>
            <el-radio value="VERY_HIGH">极高强度</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 地点 -->
        <el-form-item label="地点" prop="location">
          <el-input
            v-model="exerciseForm.location"
            placeholder="请输入运动地点（可选）"
          />
        </el-form-item>
        
        <!-- 备注 -->
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="exerciseForm.notes"
            type="textarea"
            :rows="3"
            placeholder="输入备注信息，如运动感受等（可选）"
          />
        </el-form-item>
        
        <!-- 卡路里消耗 -->
        <el-form-item v-if="showCalories">
          <el-alert
            :title="`预计消耗卡路里: ${Math.round(exerciseForm.caloriesBurned || 0)} kcal`"
            type="info"
            :description="getCaloriesDescription()"
            show-icon
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createExerciseRecord, getExerciseRecordById, updateExerciseRecord, getRecentExerciseRecords } from '@/api/exerciseRecord'
import { getAllExerciseTypes, getExerciseTypeById } from '@/api/exerciseType'
import http from '@/api/http'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const exerciseTypes = ref([])
const selectedType = ref(null)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 格式化日期为yyyy-MM-dd HH:mm:ss
const formatDateToYMDHMS = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 表单数据
const exerciseForm = ref({
  exerciseTypeId: null,
  startTime: formatDateToYMDHMS(new Date()),
  endTime: null,
  durationMinutes: 30,
  intensity: 'MEDIUM',
  location: '',
  notes: '',
  caloriesBurned: 0
})

// 表单验证规则
const rules = {
  exerciseTypeId: [
    { required: true, message: '请选择运动类型', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  durationMinutes: [
    { required: true, message: '请输入持续时间', trigger: 'blur' },
    { type: 'number', min: 1, max: 1440, message: '持续时间范围在1-1440分钟之间', trigger: 'blur' }
  ]
}

// 按分类分组的运动类型
const exerciseTypeGroups = computed(() => {
  const groups = {}
  
  exerciseTypes.value.forEach(type => {
    if (!groups[type.category]) {
      groups[type.category] = {
        category: type.category,
        types: []
      }
    }
    groups[type.category].types.push(type)
  })
  
  return Object.values(groups)
})

// 是否显示卡路里消耗信息
const showCalories = computed(() => {
  return exerciseForm.value.exerciseTypeId && exerciseForm.value.durationMinutes > 0
})

// 获取运动类型分类显示名称
const getCategoryDisplayName = (category) => {
  const categoryMap = {
    'CARDIO': '有氧运动',
    'STRENGTH': '力量训练',
    'FLEXIBILITY': '柔韧性训练',
    'BALANCE': '平衡训练',
    'SPORTS': '体育运动',
    'OTHER': '其他'
  }
  return categoryMap[category] || category
}

// 获取强度系数
const getIntensityMultiplier = (intensity) => {
  const multiplierMap = {
    'LOW': 0.8,
    'MEDIUM': 1.0,
    'HIGH': 1.2,
    'VERY_HIGH': 1.5
  }
  return multiplierMap[intensity] || 1.0
}

// 处理运动类型变更
const handleTypeChange = async (typeId) => {
  if (!typeId) {
    selectedType.value = null
    return
  }
  
  try {
    const type = await getExerciseTypeById(typeId)
    selectedType.value = type
    calculateCalories()
  } catch (error) {
    console.error('获取运动类型详情失败:', error)
  }
}

// 处理时间变更
const handleTimeChange = () => {
  if (exerciseForm.value.startTime && exerciseForm.value.endTime) {
    console.log('开始时间:', exerciseForm.value.startTime)
    console.log('结束时间:', exerciseForm.value.endTime)
    
    const start = new Date(exerciseForm.value.startTime)
    const end = new Date(exerciseForm.value.endTime)
    
    if (end <= start) {
      ElMessage.warning('结束时间必须晚于开始时间')
      exerciseForm.value.endTime = null
      return
    }
    
    // 计算时间差（分钟）
    const minutesDiff = Math.round((end - start) / (1000 * 60))
    
    // 限制最大运动时长为24小时
    if (minutesDiff > 1440) {
      ElMessage.warning('运动时长不能超过24小时(1440分钟)，已自动调整')
      // 调整结束时间为开始时间后24小时
      const maxEnd = new Date(start.getTime() + (1440 * 60 * 1000))
      exerciseForm.value.endTime = formatDateToYMDHMS(maxEnd)
      exerciseForm.value.durationMinutes = 1440
    } else {
      exerciseForm.value.durationMinutes = minutesDiff
    }
    
    calculateCalories()
  }
}

// 处理持续时间变更
const handleDurationChange = () => {
  if (exerciseForm.value.startTime && exerciseForm.value.durationMinutes) {
    // 限制最大运动时长
    if (exerciseForm.value.durationMinutes > 1440) {
      exerciseForm.value.durationMinutes = 1440
      ElMessage.warning('运动时长不能超过24小时(1440分钟)')
    }
    
    const start = new Date(exerciseForm.value.startTime)
    const end = new Date(start.getTime() + exerciseForm.value.durationMinutes * 60000)
    exerciseForm.value.endTime = formatDateToYMDHMS(end)
    
    calculateCalories()
  }
}

// 计算卡路里消耗
const calculateCalories = () => {
  if (!selectedType.value || !exerciseForm.value.durationMinutes) {
    exerciseForm.value.caloriesBurned = 0
    return
  }
  
  const intensityMultiplier = getIntensityMultiplier(exerciseForm.value.intensity)
  const calories = exerciseForm.value.durationMinutes * selectedType.value.caloriesPerMinute * intensityMultiplier
  
  // 限制最大卡路里消耗为10,000卡路里
  const maxCalories = 10000
  if (calories > maxCalories) {
    console.log(`计算的卡路里 ${calories} 超过最大限制 ${maxCalories}，已调整`)
    exerciseForm.value.caloriesBurned = maxCalories
  } else {
    exerciseForm.value.caloriesBurned = Math.round(calories * 100) / 100
  }
}

// 获取卡路里消耗描述
const getCaloriesDescription = () => {
  if (!selectedType.value) return ''
  
  const intensityName = {
    'LOW': '低强度',
    'MEDIUM': '中等强度',
    'HIGH': '高强度',
    'VERY_HIGH': '极高强度'
  }[exerciseForm.value.intensity] || '中等强度'
  
  return `基于 ${selectedType.value.name} 的基准消耗值 (${selectedType.value.caloriesPerMinute} kcal/分钟) 和 ${intensityName} 系数计算`
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请检查表单是否填写正确')
      return
    }
    
    // 特别检查exerciseTypeId
    if (!exerciseForm.value.exerciseTypeId) {
      ElMessage.warning('请选择运动类型')
      return
    }
    
    loading.value = true
    try {
      // 记录数据格式以便调试
      console.log('提交的运动数据:', {
        表单数据: exerciseForm.value,
        编辑模式: isEdit.value,
        记录ID: route.params.id
      })
      
      // 准备提交数据 - 使用最简单的数据结构
      const submitData = {
        id: isEdit.value ? Number(route.params.id) : undefined,
        exerciseTypeId: Number(exerciseForm.value.exerciseTypeId), // 只传递ID
        startTime: exerciseForm.value.startTime,
        endTime: exerciseForm.value.endTime,
        durationMinutes: Number(exerciseForm.value.durationMinutes),
        intensity: exerciseForm.value.intensity,
        location: exerciseForm.value.location || "",
        notes: exerciseForm.value.notes || "",
        caloriesBurned: Number(exerciseForm.value.caloriesBurned)
      }
      
      // 确保exerciseTypeId有值
      if (!submitData.exerciseTypeId) {
        console.error('提交数据缺少运动类型ID:', {
          表单运动类型: exerciseForm.value.exerciseTypeId,
          处理后ID: submitData.exerciseTypeId,
          原始表单: exerciseForm.value
        })
        ElMessage.error('运动类型数据错误，请重新选择运动类型')
        loading.value = false
        return
      }
      
      // 检查必填字段
      if (!submitData.exerciseTypeId) {
        ElMessage.warning('请选择运动类型')
        loading.value = false
        return
      }
      
      // 限制值范围
      if (submitData.durationMinutes > 1440) {
        submitData.durationMinutes = 1440
        console.warn('运动时长超过24小时，已自动调整为1440分钟')
      }
      
      if (submitData.caloriesBurned > 10000) {
        submitData.caloriesBurned = 10000
        console.warn('卡路里消耗超过最大值，已自动调整为10000卡路里')
      }
      
      console.log('转换后的提交数据:', {
        数据内容: submitData,
        时间格式: {
          startTime: submitData.startTime,
          endTime: submitData.endTime
        }
      })
      
      let response
      if (isEdit.value) {
        try {
          response = await updateExerciseRecord(submitData.id, submitData)
          console.log('更新运动记录响应:', {
            状态: '成功',
            响应数据: response
          })
          ElMessage.success('运动记录更新成功')
          goBack()
        } catch (updateError) {
          console.error('更新运动记录失败:', {
            错误类型: updateError.name,
            错误消息: updateError.message,
            响应状态: updateError.response?.status,
            响应数据: updateError.response?.data,
            提交数据: submitData
          })
          if (updateError.response?.data?.message) {
            ElMessage.error(updateError.response.data.message)
          } else {
            ElMessage.error('更新运动记录失败: ' + updateError.message)
          }
        }
      } else {
        try {
          response = await createExerciseRecord(submitData)
          console.log('创建运动记录响应:', {
            状态: '成功',
            响应数据: response
          })
          ElMessage.success('运动记录添加成功')
          goBack()
        } catch (createError) {
          console.error('创建运动记录失败:', {
            错误类型: createError.name,
            错误消息: createError.message,
            响应状态: createError.response?.status,
            响应数据: createError.response?.data,
            提交数据: submitData
          })
          if (createError.response?.data?.message) {
            ElMessage.error(createError.response.data.message)
          } else {
            ElMessage.error('创建运动记录失败: ' + createError.message)
          }
        }
      }
    } catch (error) {
      console.error('表单提交失败:', {
        错误类型: error.name,
        错误消息: error.message,
        错误堆栈: error.stack
      })
      ElMessage.error('操作失败，请检查表单数据是否正确')
    } finally {
      loading.value = false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/exercise-records')
}

// 加载运动类型数据
const loadExerciseTypes = async () => {
  try {
    exerciseTypes.value = await getAllExerciseTypes()
  } catch (error) {
    console.error('获取运动类型失败:', error)
    ElMessage.error('获取运动类型失败')
  }
}

// 加载运动记录详情（编辑模式）
const loadExerciseRecord = async (id) => {
  loading.value = true
  
  try {
    console.log('开始加载运动记录, ID:', id);
    
    // 首先尝试从会话存储中获取数据
    const storedRecordJson = sessionStorage.getItem('currentExerciseRecord');
    if (storedRecordJson) {
      try {
        const storedRecord = JSON.parse(storedRecordJson);
        // 确认存储的记录ID与当前请求的ID匹配
        if (storedRecord && storedRecord.id == id) {
          console.log('从会话存储中加载运动记录:', storedRecord);
          processAndSetRecordData(storedRecord);
          // 清除存储的记录，避免重复使用
          sessionStorage.removeItem('currentExerciseRecord');
          return; // 成功加载，直接返回
        }
      } catch (parseError) {
        console.error('解析会话存储中的记录失败:', parseError);
      }
    }
    
    // 尝试从API获取
    try {
      const record = await getExerciseRecordById(id);
      processAndSetRecordData(record);
      return; // 成功处理数据后直接返回
    } catch (directError) {
      console.error('直接获取运动记录详情失败，尝试备选方案:', directError);
    }
    
    // 备选方案A：使用列表页面已存在的数据
    try {
      // 备选方案：获取最近的运动记录列表并在前端过滤
      console.log('尝试备选方案：获取所有记录并在前端过滤');
      const recordsList = await getRecentExerciseRecords(50); // 获取较多记录以提高命中率
      console.log('获取到运动记录列表:', recordsList);
      
      // 在前端过滤出目标记录
      const targetRecord = Array.isArray(recordsList) 
        ? recordsList.find(r => r.id == id)
        : null;
      
      if (targetRecord) {
        console.log('在列表中找到目标记录:', targetRecord);
        processAndSetRecordData(targetRecord);
        return;
      }
    } catch (listError) {
      console.error('获取记录列表失败:', listError);
    }
    
    // 如果所有尝试都失败，显示错误
    throw new Error('无法找到指定ID的运动记录');
  } catch (error) {
    console.error('获取运动记录失败:', error);
    if (error.response) {
      console.error('错误响应状态:', error.response.status);
      console.error('错误响应数据:', error.response.data);
    }
    ElMessage.error('获取运动记录失败，即将返回列表页');
    setTimeout(() => router.push('/exercise-records'), 1500);
  } finally {
    loading.value = false;
  }
}

// 处理记录数据并设置表单
const processAndSetRecordData = (record) => {
  // 确保日期格式正确
  let processedStartTime = record.startTime;
  let processedEndTime = record.endTime;
  
  // 处理可能的ISO格式日期
  if (processedStartTime && typeof processedStartTime === 'string' && processedStartTime.includes('T')) {
    processedStartTime = processedStartTime.replace('T', ' ').substring(0, 19);
  }
  
  if (processedEndTime && typeof processedEndTime === 'string' && processedEndTime.includes('T')) {
    processedEndTime = processedEndTime.replace('T', ' ').substring(0, 19);
  }
  
  // 安全获取运动类型ID
  let typeId = null;
  if (record.exerciseType) {
    // 如果是对象，获取ID属性
    if (typeof record.exerciseType === 'object' && record.exerciseType !== null) {
      typeId = record.exerciseType.id;
    } 
    // 如果直接是ID
    else if (typeof record.exerciseType === 'number') {
      typeId = record.exerciseType;
    }
    // 如果是字符串ID
    else if (typeof record.exerciseType === 'string' && !isNaN(Number(record.exerciseType))) {
      typeId = Number(record.exerciseType);
    }
  } 
  // 如果有exerciseTypeId字段
  else if (record.exerciseTypeId) {
    typeId = typeof record.exerciseTypeId === 'number' ? record.exerciseTypeId : Number(record.exerciseTypeId);
  }
  
  // 不能获取类型ID
  if (!typeId) {
    console.error('无法获取运动类型ID:', record);
    ElMessage.error('运动记录缺少类型信息');
    return;
  }
  
  exerciseForm.value = {
    exerciseTypeId: typeId,
    startTime: processedStartTime,
    endTime: processedEndTime,
    durationMinutes: record.durationMinutes,
    intensity: record.intensity || 'MEDIUM',
    location: record.location || '',
    notes: record.notes || '',
    caloriesBurned: record.caloriesBurned || 0
  }
  
  console.log('表单数据已设置:', exerciseForm.value);
    
  // 加载运动类型详情
  handleTypeChange(typeId);
}

onMounted(async () => {
  await loadExerciseTypes()
  
  if (isEdit.value) {
    await loadExerciseRecord(route.params.id)
  }
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
}

.exercise-form {
  max-width: 600px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .el-radio-group {
    display: flex;
    flex-direction: column;
  }
  
  .el-radio {
    margin-left: 0 !important;
    margin-bottom: 10px;
  }
}
</style> 